<template>
  <div class="banner">
    <div class="banner-bg" :style="{ backgroundImage: `url(${activeFilm?.poster})` }"></div>
    <div class="swiper" ref="swiperRef">
      <div class="swiper-wrapper">
        <div class="swiper-slide" v-for="item in slides" :key="item.filmId">
          <img :src="item.poster" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, onMounted } from 'vue'
import swiper, { type Swiper } from 'swiper'
import 'swiper/swiper-bundle.css'
import type { Film } from '@/api/interface'

const props = defineProps<{
  // 当前选择的电影Id
  filmId?: number
  // 当前影院的电影列表
  slides: Film.Item[]
}>()

const emit = defineEmits(['update:filmId'])

const swiperRef = ref<HTMLDivElement | null>(null)
let mySwiper: Swiper

// 当前激活的电影
const activeFilm = computed(() => {
  if (props.filmId) {
    return props.slides.find((item) => item.filmId === props.filmId) || props.slides[0]
  } else {
    return props.slides[0]
  }
})

watch(
  () => props.slides,
  (newVal) => {
    // 通知 swiper 重新更新一下
    mySwiper && mySwiper.update()
    // 计算 当前需要激活的下标
    const index = newVal.findIndex((item) => item.filmId === props.filmId) || 0
    // 通过 slideTo 切换
    mySwiper && mySwiper.slideTo(index)
  },
  {
    flush: 'post'
  }
)

onMounted(() => {
  // console.log('onMounted', props.slides.length)
  // 计算 initialSlide
  const initialSlide = props.slides.findIndex((item) => item.filmId === props.filmId) || 0

  // console.log('初始化 swiper', swiperRef.value?.innerHTML)
  mySwiper = new swiper(swiperRef.value!, {
    initialSlide, // 设定初始化时slide的索引
    slidesPerView: 4, // 一屏显示多个 slide
    spaceBetween: 30, // slide 之间的间隔
    centeredSlides: true, // 激活的 slide 在中间
    slideToClickedSlide: true // 点击 激活
  })

  // 监听 mySwiper 的 slideChange 事件
  //    触发 父组件修改 filmId
  mySwiper.on('slideChange', (ins) => {
    const filmId = props.slides[ins.activeIndex].filmId
    emit('update:filmId', filmId)
  })
})
</script>

<style lang="scss" scoped>
.banner {
  box-sizing: border-box;
  height: 160px;
  padding: 15px 0;
  position: relative;
  background-color: #ccc;
  overflow: hidden;
}

.banner-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  filter: blur(30px);
}

.swiper {
  width: 100%;
  height: 100%;
}

.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;

  display: flex;
  justify-content: center;
  align-items: center;
  transition: 300ms;
  transform: scale(0.8);

  img {
    display: block;
    width: 100%;
    height: 100%;
  }
}
.swiper-slide-active {
  transform: scale(1);
}
</style>
